#!/bin/bash
#This script was written by Matthew Vona of ARB to support the CarbLogger 
#project 6/6/2011 for Ubuntu 11.04 using network manager to connect via
#a wireless broadband router. The script requires that networkmanager can use
#the connection, and is available as a droptown from the desktop applet.
usage()
{
echo "Proper usage is $0 <connection name>"
}

#USER CONFIGURATION:
#CON_NAME is the name of the connection you want to use.
CON_NAME=$1;
#USE OPTIONAL TO RUN COMMANDS AFTER CONNECTION IS RE-ESTABLISHED
#IN THIS CASE WE WANT TO UPDATE DYNAMIC DNS WITH OUr CURRENT IP
OPTIONAL="ddclient"
#SINCE WE WILL RUN THIS USING CRON, CHECK TO SEE THAT IT IS NOT ALREADY RUNNING
instances=`ps -fe | grep $0 | grep -v "grep"`
if [ $instances -gt 1 ]; then
{
exit
}
fi
#CHECK FOR THE CORRENT NUMBER OF PARAMETERS
if [ $# != "1" ]; then
{
usage
exit 1
}
fi 
#SEE IF WE ARE CONNECTED
CONNECTED=`nmcli con status id $CON_NAME | wc -l`
#IF NOT CONNECTED, TRY TO RECONNECT
while [ $CONNECTED -lt 2 ]
do
	#MAKE SURE THE CONNECTION IS NOW AVAILABLE
	#IF NOT SLEEP
	is_available=`nmcli con | grep $CONNECT | wc -l`
	#IF IT BECOMES AVAILABLE, START IT UP
	if [ $is_available -gt 0 ]; then
	{
		nmcli con up id $CON_NAME
		sleep 50
		CONNECTED=`nmcli con status id $CON_NAME | wc -l`
	}
	fi
	sleep 300
done
opt_alive=`ps -fe | grep "$OPTIONAL" | grep -v "grep" | wc -l`
if [ $opt_alive -eq 0 ]; then
{
	$OPTIONAL
}
fi
exit
